package cn.jtfadmin.base.lang.common.utils;

import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 系统工具
 * @author jtf
 * @since 0.0.1
 */
public class IpUtils {

    /**
     *  获取本机ipv4地址
     * @return 获取本机ipv4地址
     */
    public static List<String> getLocalIpV4()  {
        List<String> list = new ArrayList<>();
        Enumeration<NetworkInterface> networkInterfaces = null;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            return list;
        }
        while (networkInterfaces.hasMoreElements()){
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                InetAddress address = interfaceAddress.getAddress();
                if( address instanceof Inet4Address){
                    list.add(address.getHostAddress());
                }

            }
        }
        return list;
    }

    /**
     *  获取本机ipv6地址
     * @return 获取本机ipv6地址
     */
    public static List<String> getLocalIpV6()  {
        List<String> list = new ArrayList<>();
        Enumeration<NetworkInterface> networkInterfaces = null;
        try {
            networkInterfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            return list;
        }
        while (networkInterfaces.hasMoreElements()){
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            List<InterfaceAddress> interfaceAddresses = networkInterface.getInterfaceAddresses();
            for (InterfaceAddress interfaceAddress : interfaceAddresses) {
                InetAddress address = interfaceAddress.getAddress();
                if( address instanceof Inet6Address){
                    list.add(address.getHostAddress());
                }

            }
        }
        return list;
    }


}
